package com.anhry.app.safety.manage.oa.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.stereotype.Service;

import com.anhry.app.safety.manage.oa.bean.TbOaCallMsg;
import com.anhry.app.safety.manage.oa.bean.TbOaCallMsgView;
import com.anhry.app.safety.manage.oa.bean.TbOaPersonCall;
import com.anhry.app.safety.manage.oa.service.CallService;
import com.anhry.app.safety.manage.system.bean.TbUser;
import com.anhry.app.safety.util.DateFormater;
import com.anhry.app.safety.util.Loggers;
import com.anhry.app.safety.util.dao.UtilDao;
/**
 * 
 * @author chen
 * @date 2012-8-20
 */
@Service
public class CallServiceImpl implements CallService {

	private static Logger logger = Logger.getLogger(CallServiceImpl.class);

	@Resource
	private UtilDao utilDao;

	public UtilDao getUtilDao() {
		return utilDao;
	}
	
	public List<TbOaPersonCall> loadPerCallList(String keyWord,String beginTime, String endTime,TbUser user,String forward,String isSend, final int startRow, final int size)throws Exception {
		if(null==keyWord){
			keyWord = "";
		}
		StringBuffer sbf = new StringBuffer("from TbOaPersonCall pc left join fetch pc.tbUser where pc.callContent like '%"+keyWord+"%'");
		if(size==0){
			sbf = new StringBuffer("select count(*) from TbOaPersonCall pc where pc.callContent like '%"+keyWord+"%'");
		}
		if(null!=user){
			sbf.append(" and pc.tbUser.id='"+user.getId()+"'");
		}
		if(null!=beginTime && !"".equals(beginTime)){
			sbf.append(" and to_char(pc.callTime,'yyyy-mm-dd') >= '"+beginTime+"'");
		}
		if(null!=endTime && !"".equals(endTime) ){
			sbf.append(" and to_char(pc.callTime,'yyyy-mm-dd') <= '"+endTime+"'");
		}
		if(null!=isSend && !"".equals(isSend)){
			sbf.append(" and pc.isSend='"+isSend+"'");
		}
		sbf.append(" and pc.isDele=0 order by pc.callDate desc");
		final String sql = sbf.toString();
		Session session=this.getUtilDao().getHibernateSession();
		List list = new ArrayList();
		try {
			Query query = null;							
			query = session.createQuery(sql);
			if(size!=0){
				query.setFirstResult(startRow);
				query.setMaxResults(size);
			}
			list = query.list();
			return list;
		} catch (Exception t) {
			t.printStackTrace();
			Loggers.error("OADaoImpl:List<TbOaPersonCall> loadPerCallList(String keyWord,String beginTime, String endTime, final int startRow, final int size)" + t.getMessage());
			try {
				throw t;
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}finally{
			if(session!=null&&session.isOpen()){
				session.close();
			}
			
		}
		return list;
	}
	
	public List<TbOaCallMsgView> loadCallMsgList(String keyWord,String beginTime, String endTime, TbUser user,String isRead, final int startRow,final int size) throws Exception {
		if(null==keyWord){
			keyWord = "";
		}
		StringBuffer sbf = new StringBuffer("from TbOaCallMsgView msg where msg.msgContent like '%"+keyWord+"%' and msg.isDele=0 and msg.tbUser.id='"+user.getId()+"' and msg.userTypes=0");
		if(size==0){
			sbf = new StringBuffer("select count(*) from TbOaCallMsgView msg where msg.msgContent like '%"+keyWord+"%' and msg.isDele=0 and msg.tbUser.id='"+user.getId()+"' and msg.userTypes=0");
		}
		if(null!=beginTime && !"".equals(beginTime)){
			sbf.append(" and to_char(msg.msgTime,'yyyy-mm-dd') >= '"+beginTime+"'");
		}
		if(null!=endTime && !"".equals(endTime) ){
			sbf.append(" and to_char(msg.msgTime,'yyyy-mm-dd') <= '"+endTime+"'");
		}
		if(null!=isRead && !"".equals(isRead)){
			sbf.append(" and msg.isRead='"+isRead+"'");
		}
		sbf.append(" and (msg.callType=0 or msg.callType=2) order by msg.msgTime desc");// 
		final String sql = sbf.toString();
		
		Session session=this.getUtilDao().getHibernateSession();
		List list = new ArrayList();
		try {
			Query query = null;							
			query = session.createQuery(sql);
			if(size>0){
				query.setFirstResult(startRow);
				query.setMaxResults(size);
			}
			list = query.list();
			return list;
		} catch (Exception t) {
			t.printStackTrace();
			Loggers.error("OADaoImpl:List<TbOaCallMsg> loadCallMsgList(String keyWord,String beginTime, String endTime, TbUser user, final int startRow,final int size)" + t.getMessage());
			try {
				throw t;
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}finally{
			if(session!=null&&session.isOpen()){
				session.close();
			}
		}
		return list;
	}
	
	public List<TbOaPersonCall> loadPerCallList() throws Exception {
		return (List<TbOaPersonCall>) this.getUtilDao().getHqlQuery("from TbOaPersonCall call where call.isSend=0 and call.isDele=0");
	}
	
	public List<TbOaPersonCall> loadPerCallList(String keyWord,String callTypes, String beginTime, String endTime,String keyUser,String userUnit,String userDept, String isSends, final int startRow, final int size) throws Exception {
		if(null==keyWord){
			keyWord = "";
		}
		StringBuffer sbf = new StringBuffer("from TbOaPersonCall pc left join fetch pc.tbUser left join fetch pc.tbUser.tbUserUnit left join fetch pc.tbUser.tbUserDept  where pc.callContent like '%"+keyWord+"%'");
		if(size==0){
			sbf = new StringBuffer("select count(*) from TbOaPersonCall pc where pc.callContent like '%"+keyWord+"%'");
		}
		if(null!=callTypes && !"".equals(callTypes)){
			sbf.append(" and pc.callType='"+callTypes+"'");
		}
		if(null!=beginTime && !"".equals(beginTime)){
			sbf.append(" and to_char(pc.callTime,'yyyy-mm-dd') >= '"+beginTime+"'");
		}
		if(null!=endTime && !"".equals(endTime) ){
			sbf.append(" and to_char(pc.callTime,'yyyy-mm-dd') <= '"+endTime+"'");
		}
		if(null!=keyUser && !"".equals(keyUser)){
			sbf.append(" and pc.tbUser.userRealName like '%"+keyUser+"%'");
		}
		if(null!=userUnit && !"".equals(userUnit)){
			if(null!=userDept && !"".equals(userDept)){
				sbf.append(" and pc.tbUser.tbUserDept = "+Long.parseLong(userDept)+"");
			}else{
				sbf.append(" and pc.tbUser.tbUserUnit= "+Long.parseLong(userUnit)+"");
			}
		}
		if(null!=isSends && !"".equals(isSends)){
			sbf.append(" and pc.isSend='"+isSends+"'");
		}
		sbf.append(" order by pc.callDate desc");
		final String sql = sbf.toString();
		Session session=this.getUtilDao().getHibernateSession();
		List list = new ArrayList();
		try {
			Query query = null;							
			query = session.createQuery(sql);
			if(size!=0){
				query.setFirstResult(startRow);
				query.setMaxResults(size);
			}
			list = query.list();
			return list;
		} catch (Exception t) {
			t.printStackTrace();
			Loggers.error("CAllServiceImpl:List<TbOaPersonCall> loadPerCallList" + t.getMessage());
			try {
				throw t;
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}finally{
			if(session!=null&&session.isOpen()){
				session.close();
			}
		}
		return list;
	}
	
	//汇总列表 查询条件修改后 重载
	public List<TbOaPersonCall> loadPerCallList(String keyWord,String callTypes, String beginTime, String endTime,String keyUser,String wherehql, String isSends, final int startRow, final int size) throws Exception {
		if(null==keyWord){
			keyWord = "";
		}
		StringBuffer sbf = new StringBuffer("from TbOaPersonCall pc left join fetch pc.tbUser left join fetch pc.tbUser.tbUserUnit left join fetch pc.tbUser.tbUserDept  where pc.callContent like '%"+keyWord+"%'");
		if(size==0){
			sbf = new StringBuffer("select count(*) from TbOaPersonCall pc where pc.callContent like '%"+keyWord+"%'");
		}
		if(null!=callTypes && !"".equals(callTypes)){
			sbf.append(" and pc.callType='"+callTypes+"'");
		}
		if(null!=beginTime && !"".equals(beginTime)){
			sbf.append(" and to_char(pc.callTime,'yyyy-mm-dd') >= '"+beginTime+"'");
		}
		if(null!=endTime && !"".equals(endTime) ){
			sbf.append(" and to_char(pc.callTime,'yyyy-mm-dd') <= '"+endTime+"'");
		}
		if(null!=keyUser && !"".equals(keyUser)){
			sbf.append(" and pc.tbUser.userRealName like '%"+keyUser+"%'");
		}
		if(null!=wherehql && !"".equals(wherehql)){
			sbf.append(wherehql);
		}
		if(null!=isSends && !"".equals(isSends)){
			sbf.append(" and pc.isSend='"+isSends+"'");
		}
		sbf.append(" order by pc.callDate desc");
		final String sql = sbf.toString();
		Session session=this.getUtilDao().getHibernateSession();
		List list = new ArrayList();
		try {
			Query query = null;							
			query = session.createQuery(sql);
			if(size!=0){
				query.setFirstResult(startRow);
				query.setMaxResults(size);
			}
			list = query.list();
			return list;
		} catch (Exception t) {
			t.printStackTrace();
			Loggers.error("CAllServiceImpl:List<TbOaPersonCall> loadPerCallList" + t.getMessage());
			try {
				throw t;
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}finally{
			if(session!=null&&session.isOpen()){
				session.close();
			}
		}
		return list;
	}
	
	public String loadDeptCallNums(String deptType, TbUser user, String dateType) throws Exception {
		Calendar ca = Calendar.getInstance();
		int year = ca.get(Calendar.YEAR);
		int month = ca.get(Calendar.MONTH)+1;
		int quarter = DateFormater.getQuarter(ca);
		String nums = "0";
		StringBuffer sbf = new StringBuffer();
		try {
			if("0".equals(deptType)){//管理员
				sbf.append("select count(*) from TbOaPersonCall n where n.tbUser.id='"+user.getId()+"'");
			}else if("1".equals(deptType)){//科室用户
				sbf.append("select count(*) from TbOaPersonCall n where n.tbUser.tbUserDept.id="+user.getTbUserDept().getId()+"");
			}else{//行业或者属地用户
				sbf.append("select count(*) from TbOaPersonCall n where n.tbUser.tbUserUnit.id="+user.getTbUserUnit().getId()+"");
			}
			if("0".equals(dateType)){//年
				sbf.append(" and n.callYear='"+String.valueOf(year)+"'");
			}else if("1".equals(dateType)){//季度
				sbf.append(" and n.callYear='"+String.valueOf(year)+"' and n.callQuarter='"+String.valueOf(quarter)+"'");
			}else{//月
				sbf.append(" and n.callYear='"+String.valueOf(year)+"' and n.callMonth='"+String.valueOf(month)+"'");
			}
			List list = (List)this.getUtilDao().getHqlQuery(sbf.toString());
			
			if(null!=list && list.size()>0){
				nums = list.get(0).toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("OADaoImpl:String loadDeptCallNums(String deptType, TbUser user, String dateType)" + e.getMessage());
		}
		return nums;
	}

	public List<TbOaCallMsg> loadCallReadList(Long id, String readType, final int startRow, final int size) throws Exception {
		StringBuffer sbf = new StringBuffer("from TbOaCallMsg c left join fetch c.tbUser left join fetch c.tbUser.tbUserUnit left join fetch c.tbUser.tbUserDept left join fetch c.tbCorpInfo left join fetch c.tbCorpInfo.tbCounty left join fetch c.tbCorpInfo.tbStreet left join fetch c.tbCorpInfo.tbVillage  where c.tbPersonCall.id='"+id+"'");// and (c.msgType=0 or c.msgType=2)
		if(size==0){
			sbf = new StringBuffer("select count(*) from TbOaCallMsg c where c.tbPersonCall.id='"+id+"'");// and (c.msgType=0 or c.msgType=2)
		}
		if(null!=readType && !"".equals(readType)){
			sbf.append(" and c.isRead='"+readType+"'");
		}
		sbf.append(" order by c.id");
		final String sql = sbf.toString();
		Session session=this.getUtilDao().getHibernateSession();
		List list = new ArrayList();
		try {
			Query query = null;							
			query = session.createQuery(sql);
			if(size!=0){
				query.setFirstResult(startRow);
				query.setMaxResults(size);
			}
			list = query.list();
			return list;
		} catch (Exception t) {
			t.printStackTrace();
			Loggers.error("OADaoImpl:List<TbOaCallMsg> loadCallReadList(String id, String readType, int startRow, int size)" + t.getMessage());
			try {
				throw t;
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}finally{
			if(session!=null&&session.isOpen()){
				session.close();
			}
		}
		return list;
	}
	
	public String deptCallInNums(String deptType, TbUser user, String dateType, String callType,String msgType,String way) throws Exception {
		String size = "";
		Calendar ca = Calendar.getInstance();
		int year = ca.get(Calendar.YEAR);
		int month = ca.get(Calendar.MONTH)+1;
		int quarter = DateFormater.getQuarter(ca);
		List list = null;
		StringBuffer sbf = new StringBuffer();
		Session s = this.utilDao.getHibernateSession();
		try{
			if(way != null && "0".equals(way)){//提醒设置条数统计
				sbf.append("select count(*) from tb_oa_call_msg msg " +
						"left join tb_oa_person_call ca on msg.per_call_id=ca.id " +
						"left join tb_user u on u.id=msg.msg_user " +
						"left join tb_user_dept unit on unit.id=u.user_unit " +
						"where msg.is_dele='0' and ca.is_dele='0'");	
			}else{//提醒接收次数统计
				sbf.append("select count(*) from tb_oa_call_msg msg " +
						"left join tb_oa_person_call ca on msg.per_call_id=ca.id " +
						"left join tb_user u on u.id=msg.adds_user " +
						"left join tb_user_dept unit on unit.id=u.user_unit " +
				"where msg.is_dele='0' and ca.is_dele='0'");
			}
			if(msgType != null && !"".equals(msgType)){//消息类型
				sbf.append(" and msg.msg_type='"+msgType+"'");
			}
			if(deptType != null && !"".equals(deptType)){//管理部门统计
				sbf.append(" and unit.dept_class='"+deptType+"'");
			}else{//当前用户统计
				if(way != null && "0".equals(way)){
					sbf.append("and msg.msg_user='"+user.getId()+"'");//提醒发送者为当前用户
				}else{
					sbf.append("and msg.adds_user='"+user.getId()+"'");	//提醒接收者为当前用户
				}
			}
			if(callType != null && !"".equals(callType)){
				sbf.append(" and ca.call_type='"+callType+"'");
			}
			if("0".equals(dateType)){//年
				sbf.append(" and msg.msg_year='"+String.valueOf(year)+"'");
			}else if("1".equals(dateType)){//季度
				sbf.append(" and msg.msg_year='"+String.valueOf(year)+"' and msg.msg_quarter='"+String.valueOf(quarter)+"'");
			}else{//月
				sbf.append(" and msg.msg_year='"+String.valueOf(year)+"' and msg.msg_month='"+String.valueOf(month)+"'");
			}	
			SQLQuery query = s.createSQLQuery(sbf.toString());
			list = query.list();
			if(list != null && list.size()>0){
				Object temp = (Object) list.get(0);
				if(temp != null && !"".equals(temp.toString())){
					size = temp.toString();
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(s != null && s.isOpen()){
				s.close();
			}
		}
		return size;
	}
	
	public String deptCallSetNums(String deptType, TbUser user, String dateType, String callType) throws Exception {
		String size = "";
		Calendar ca = Calendar.getInstance();
		int year = ca.get(Calendar.YEAR);
		int month = ca.get(Calendar.MONTH)+1;
		int quarter = DateFormater.getQuarter(ca);
		StringBuilder sbf = new StringBuilder();
		Session s = utilDao.getHibernateSession();
		List list = null;
		try{
			sbf.append("select count(*) from tb_oa_person_call t " +
					"left join tb_user u on u.id = t.call_user " +
					"left join tb_user_dept unit on unit.id = u.user_unit " +
					"where t.is_dele='0'");
			if(deptType != null && !"".equals(deptType)){
				sbf.append(" and unit.dept_class='"+deptType+"'");
			}
			if(callType != null && !"".equals(callType)){
				sbf.append(" and t.call_type='"+callType+"'");
			}
			if(deptType != null && !"".equals(deptType)){
				sbf.append(" and unit.dept_class='"+deptType+"'");
			}else{
				sbf.append(" and t.call_user='"+user.getId()+"'");
			}
			if("0".equals(dateType)){//年
				sbf.append(" and t.call_year='"+String.valueOf(year)+"'");
			}else if("1".equals(dateType)){//季度
				sbf.append(" and t.call_year='"+String.valueOf(year)+"' and t.call_quarter='"+String.valueOf(quarter)+"'");
			}else{//月
				sbf.append(" and t.call_year='"+String.valueOf(year)+"' and t.call_month='"+String.valueOf(month)+"'");
			}	
			SQLQuery query = s.createSQLQuery(sbf.toString());
			list = query.list();
			if(list != null && list.size()>0){
				Object temp = (Object) list.get(0);
				if(temp != null && !"".equals(temp.toString())){
					size = temp.toString();
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(s != null && s.isOpen()){
				s.close();
			}
		}
		return size;
	}
	
	/**
	 * 取得所有未发送的提醒，对现时间比较
	 * @throws Exception
	 */
	public void SendCall()throws Exception{
		Date now = new Date();
	    //SmsSend send = new SmsSend();
	    //String[] corpArray = (String[])null;
	    //String[] userArray = (String[])null;
	    //TbshyCorpInfo corp = null;
	    //TbshyCorpPersonal personal = null;
	    //TbUser tbshyUser = null;
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	    try{
	    	
	    	List callList = this.loadPerCallList();
	    	if(null!=callList && callList.size() > 0){
	    		for(int i = 0; i < callList.size(); i++){
	    			TbOaPersonCall call = (TbOaPersonCall)callList.get(i);
	    			if(call.getCallTime().before(now)){
	    				call.setIsSend("1");
	  		          	this.utilDao.update(call);
	  		          	Loggers.info(sdf.format(now) + "触发了提醒");
	    			}
//		    			if(call.getCallAddsCorp() != null && call.getIsCorper() != null && "0".equals(call.getIsCorper())) {
//		    				corpArray = call.getCallAddsCorp().split(",");
//		    				if(corpArray != null && corpArray.length > 0){
//		    					for (int j = 0; j < corpArray.length; j++){
//		    		                corp = (TbshyCorpInfo)this.utilDao.getObjectById(TbshyCorpInfo.class, corpArray[j]);
//		    		                if(corp != null && corp.getPersonalFzr() != null){
//		    		                	personal = (TbshyCorpPersonal)this.utilDao.getObjectById(TbshyCorpPersonal.class, corp.getPersonalFzr().getId());
//		    		                	send.smsSend(personal.getPersonalMobile(), call.getCallContent(), call.getTbshyUser());
//		    		                }
//		    					}
//		    				}
//		    			}else if(call.getCallAddsCorp() != null && call.getIsCorper() != null && "1".equals(call.getIsCorper())) {
//				            corpArray = call.getCallAddsCorp().split(",");
//				            if(corpArray != null && corpArray.length > 0){
//				            	for(int j = 0; j < corpArray.length; j++) {
//				            		corp = (TbshyCorpInfo)this.utilDao.getObjectById(TbshyCorpInfo.class, corpArray[j]);
//				            		if (corp != null && corp.getPersonalAqfzr() != null) {
//				            			personal = (TbshyCorpPersonal)this.utilDao.getObjectById(TbshyCorpPersonal.class, corp.getPersonalAqfzr().getId());
//				            			send.smsSend(personal.getPersonalMobile(), call.getCallContent(), call.getTbshyUser());
//				            		}
//				            	}
//				            }
//		    			}
//			          if (call.getCallAddsUser() != null) {
//			        	  userArray = call.getCallAddsUser().split(",");
//			        	  if ((userArray != null) && (userArray.length > 0)) {
//			        		  for (int j = 0; j < userArray.length; j++) {
//			        			  tbshyUser = (TbshyUser)this.utilDao.getObjectById(TbshyUser.class, userArray[j]);
//			        			  if ((tbshyUser != null) && (tbshyUser.getUserPhone() != null)) {
//			        				  send.smsSend(tbshyUser.getUserPhone(), call.getCallContent(), call.getTbshyUser());
//			        			  }
//			        		  }
//			        	  }
//			          }
	        }
	      }
	    }catch (Exception e){
	    	e.printStackTrace();
	    	Loggers.info("CallServiceImpl中SendCall()方法：" + e.getMessage());
	    }
		
	}
	
	/**
	 * 查询未读 提醒
	 */

	public int getNotReadCallSize(TbUser user)
			throws Exception {
		StringBuffer sbf = new StringBuffer();
			sbf = new StringBuffer(
					"select count(*) from TbOaCallMsg msg where msg.isDele=0 and msg.tbUser.id='"
							+ user.getId() + "' and msg.isRead=0");
		final String sql = sbf.toString();
		Session s = utilDao.getHibernateSession();
		List list = new ArrayList();
		try {
			Query query = null;
			query = s.createQuery(sql);
			list = query.list();
		}finally{
			if(s!=null&&s.isOpen()){
				s.close();
			}
		}	
		return  Integer.parseInt(list.get(0).toString());
	}
	
	
}
